package com.flismax.mysms.sendsms;

import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.telephony.SmsManager;

import com.flismax.mysms.util.Key;

/**
 * Class used to send message
 * 
 * @author DIZAII
 * 
 */
public class SmsSend {

	private Context context;

	/**
	 * Used to send message
	 */
	private SmsManager smsManager;

	/**
	 * Used to listen when sms have been sent
	 */
	private BroadcastSendSms broadcastSendSMS;

	/**
	 * Used to listen when sms have been delivered
	 */
	private BroadcastDeliveredSms broadcastDeliveredSMS;

	/**
	 * Constructor
	 * 
	 * @param context
	 */
	public SmsSend(Context context) {
		this.context = context;
		smsManager = SmsManager.getDefault();
		broadcastSendSMS = new BroadcastSendSms();
		broadcastDeliveredSMS = new BroadcastDeliveredSms();
	}

	/**
	 * Method used to send a text base SMS
	 * 
	 * @param phoneNumber
	 *            The phone number to sent message to
	 * @param message
	 *            The body of the message to send
	 * 
	 */
	public void send(String phoneNumber, String message) {
		smsManager.sendTextMessage(phoneNumber, null, message, null, null);
	}

	/**
	 * 
	 * @param phoneNumber
	 * @param message
	 */
	public void sendWithListenBroadcast(String phoneNumber, String message) {

		// Create pending intent receiver when the message is successfully sent
		// or failed
		PendingIntent sentIntent = PendingIntent.getBroadcast(context, 0,
				new Intent(Key.SENT), 0);

		// Create pending intent receiver when the message is delivered to the
		// recipient.
		PendingIntent deliveryIntent = PendingIntent.getBroadcast(context, 0,
				new Intent(Key.DELIVERED), 0);

		// we send message
		smsManager.sendTextMessage(phoneNumber, null, message, sentIntent,
				deliveryIntent);
	}

	/**
	 * Register receiver send message and delivered message
	 */
	public void registerReceiver() {
		// register receiver when have been sent message with action SMS_SENT
		context.registerReceiver(broadcastSendSMS, new IntentFilter(Key.SENT));

		// register receiver when have been delivered message with action
		// SMS_DELIVERED
		context.registerReceiver(broadcastDeliveredSMS, new IntentFilter(
				Key.DELIVERED));
	}

	/**
	 * Unregister receiver for send message and delivered message
	 */
	public void unregisterReceiver() {
		// unregister receiver delivered message
		context.unregisterReceiver(broadcastDeliveredSMS);

		// unregister receiver send message
		context.unregisterReceiver(broadcastSendSMS);
	}
}
